package com.wdz.controller;

import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wdz.article_comment.entity.ArticleComment;
import com.wdz.article_comment.service.IArticleCommentService;
import com.wdz.entity.ArticleCommentsA;
import com.wdz.fegin.WebSocketFegin;
import com.wdz.http.Response;
import com.wdz.kafka.Product;
import com.wdz.kafka.constant.Topics;
import com.wdz.kafka.entity.EmailEntity;
import com.wdz.redis.RedisUtil;
import com.wdz.service.IRemarkService;
import com.wdz.utils.RedisFieldName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.ExecutionException;

/**
 * 留言有关的操作
 */
@RestController
public class RemarkController {
    @Autowired
    private IArticleCommentService iArticleCommentService;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    @Autowired
    private WebSocketFegin webSocketFegin;

    /**
     * 添加留言
     * @param articleComment
     * @return
     */
    @PostMapping("/publishRemark")
    public Response publishRemark(@RequestBody ArticleComment articleComment){
        iArticleCommentService.insert(articleComment);
        if(!StringUtils.isEmpty(articleComment.getEmail())){
            RedisUtil redisUtil = RedisUtil.init();
            MailUtil.send(articleComment.getEmail(),"非常感谢您的留言，我会尽快回复您的问题，请注意邮箱查收","感谢函",true);
            //try {
                //product.sendEmail(Topics.EMAILS,"sendEmail",emailEntity);
            //} catch (ExecutionException | InterruptedException e) {
                //e.printStackTrace();
           // }

            redisUtil.lSet(RedisFieldName.ARTICLECOMMENTEMAILS,articleComment.getId()+","+articleComment.getEmail());
        }
        MultiValueMap<String, String> param = new LinkedMultiValueMap<String,String>();
        JSONObject d = new JSONObject();
        d.put("id",articleComment.getId());
        d.put("type",2);
        d.put("userId",articleComment.getUserId());
        d.put("userName",articleComment.getUserName());
        d.put("userImage",articleComment.getUserImage());
        d.put("content",articleComment.getContent());
        d.put("createDate",articleComment.getCreateDate());
        Response re = Response.success(d);
        re.setCode(1);
        param.add("d",re.toJsonString());
        HttpEntity<MultiValueMap<String, String>> request =
                new HttpEntity<MultiValueMap<String, String>>(param,null);
        //方式1（restTemplate）
        ServiceInstance instance = loadBalancerClient.choose("bk_ht_center");
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity("http://"+instance.getHost()+":"+instance.getPort()+"/api/sendAdmin", request,JSONObject.class);
        if(responseEntity.getStatusCode().is2xxSuccessful()){
            Map<String,Object> r = responseEntity.getBody();
            System.out.println(r.toString());
            if((int)r.get("status") !=0 ){
                return Response.error();
            }
        }
        //方式2(fegin)
        /*Response response = webSocketFegin.sendAdmin(articleComment.toString());
        System.out.println(response.toJsonString());
        if(response.getStatus() != 0){
            return Response.error();
        }*/
        return Response.success(articleComment);
    }
    //@Autowired
    //private Product product;

    /**xxb
     * 管理员回复留言
     */
    @PostMapping("/adminReplyRemark")
    public Response adminReplyRemark(@RequestBody ArticleComment articleComment) throws ExecutionException, InterruptedException {
        iArticleCommentService.insert(articleComment);
        RedisUtil redisUtil = RedisUtil.init();
        List<Object> list = redisUtil.lGet(RedisFieldName.ARTICLECOMMENTEMAILS,0,-1);
        int size = list.size();
        String str;
        for(int i=0;i<size;i++){
            str = list.get(i).toString();
            if((articleComment.getCommentId()).equals(str.substring(0,str.indexOf(",")))) {
                //EmailEntity emailEntity = new EmailEntity();
                //emailEntity.setToEmail(str.substring(str.indexOf(","),str.length()));
                //emailEntity.setContent("<p>您的留言内容："+iArticleCommentService.selectById(articleComment.getCommentId()).getContent()
                //        +"</p><p>我的回复："
                //        +articleComment.getContent()+"</p>");
                //emailEntity.setTitle("东哲博客回复留言");
                //product.sendEmail(Topics.EMAILS,"sendEmail",emailEntity);
                MailUtil.send(str.substring(str.indexOf(","),str.length()),"<p>您的留言内容："+iArticleCommentService.selectById(articleComment.getCommentId()).getContent()
                                +"</p><p>我的回复："
                                +articleComment.getContent()+"</p>","way博客回复留言",true);
            }
            }
        return Response.success();
    }
    @Autowired
    private IRemarkService iRemarkService;
    /**
     * 分页查询留言
     */
    @PostMapping("/pageRemarks")
    public Response pageRemarks(@RequestParam int pageNo,@RequestParam int pageSize){
        Map<String,Object> data = new HashMap<>();
        data.put("total",iArticleCommentService.selectCount(new EntityWrapper<ArticleComment>().where("type={0}",2)));
        data.put("data",iRemarkService.pageRemarks(pageNo, pageSize));
        return Response.success(data);
    }
    private List<ArticleCommentsA> dgPageRemarks(List<ArticleComment> articleComments){
        List<ArticleCommentsA> articleCommentsAS = new ArrayList<>();
        if(articleComments.isEmpty()){
            return articleCommentsAS;
        }
        return dgPageRemarks(articleCommentsAS,articleComments,0,articleComments.size());
    }
    private List<ArticleCommentsA> dgPageRemarks(List<ArticleCommentsA> articleComments,List<ArticleComment> articleCommentsAS,int index,int length){
        if(index >= length){
            return articleComments;
        }
        ArticleCommentsA articleCommentsA = new ArticleCommentsA();
        ArticleComment articleComment = articleCommentsAS.get(index);
        articleCommentsA.setId(articleComment.getId());
        articleCommentsA.setCommentId(articleComment.getCommentId());
        articleCommentsA.setContent(articleComment.getContent());
        articleCommentsA.setCreateDate(articleComment.getCreateDate());
        articleCommentsA.setUserId(articleComment.getUserId());
        articleCommentsA.setUserName(articleComment.getUserName());
        articleCommentsA.setUserImage(articleComment.getUserImage());
        if(iArticleCommentService.selectCount(new EntityWrapper<ArticleComment>().where("comment_id={0} and user_id={1}",articleComment.getId(),0))>0){
            articleCommentsA.setRemarkStatus(1);
        }else{
            articleCommentsA.setRemarkStatus(0);
        }
        articleComments.add(articleCommentsA);
        index++;
        return dgPageRemarks(articleComments,articleCommentsAS,index,length);
    }
    /**
     * 分页查询留言并携带是否已读的状态
     */
    @GetMapping("/remark/{pageNo}/{pageSize}")
    public Response getRemarks(@PathVariable int pageNo,@PathVariable int pageSize){
        Map<String,Object> data = new HashMap<>();
        data.put("total",iArticleCommentService.selectCount(new EntityWrapper<ArticleComment>().where("type={0}",2)));
        data.put("data",dgPageRemarks(iArticleCommentService.selectPage(new Page<>(pageNo,pageSize),new EntityWrapper<ArticleComment>().where("type={0}",2).orderBy("create_date",false)).getRecords()));
        return Response.success(data);
    }
    /**
     * 删除单条留言
     */
    @DeleteMapping("/remark/{id}")
    public Response delete(@PathVariable String id){iArticleCommentService.deleteById(id); return Response.success();}
    /**
     * 查询单条留言
     */
    @GetMapping("/remark/{id}")
    public Response get(@PathVariable String id){return Response.success(iArticleCommentService.selectById(id));}
    /**
     * 精选留言
     */
    @GetMapping("/remark/beCarefullyChosen")
    public List<String> beCarefullyChosen(){

        return null;
    }
}
